package com.mayikt.swagger.filter;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Splitter;
import com.google.common.util.concurrent.RateLimiter;
import com.mayikt.swagger.constant.GateWayConstant;
import com.mayikt.swagger.service.SeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.RequestPath;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;


@Component
public class SeckillFilter implements GlobalFilter {

    @Autowired
    private SeckillService seckillService;
    @Value("${gateway.seckill.intercept.url}")
    private List<String> gatewaySeckillInterceptUrl;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpResponse response = exchange.getResponse();
        ServerHttpRequest request = exchange.getRequest();
        HttpHeaders header = response.getHeaders();
        header.add("Content-Type", "application/json; charset=UTF-8");
        RequestPath path = request.getPath();
        // 排除请求
        boolean resultExist = existSeckillUrl(path.value());
        if (!resultExist) {
            // 直接放行
            return chain.filter(exchange);
        }
        try {
            String userPhone = getParam(request.getURI().getQuery(), "userPhone");
            String seckillId = getParam(request.getURI().getQuery(), "seckillId");
            seckillService.seckill(userPhone, seckillId);
            return chain.filter(exchange);
        } catch (Exception e) {
            JSONObject jsonObject = setResultErrorMsg("当前访问用户过多，请稍后重试");
            DataBuffer buffer = response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
            return response.writeWith(Mono.just(buffer));
        }
    }

    public static String getParam(String url, String name) {
        String params = url.substring(url.indexOf("?") + 1, url.length());
        Map<String, String> split = Splitter.on("&").withKeyValueSeparator("=").split(params);
        return split.get(name);
    }

    public boolean existSeckillUrl(String url) {
        return gatewaySeckillInterceptUrl.contains(url);
    }

    private JSONObject setResultErrorMsg(String msg) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "500");
        jsonObject.put("msg", msg);
        return jsonObject;
    }
}